package cn.demo.um.support.factory;

import cn.demo.common.utils.DictUtils;
import cn.demo.um.domain.UmAttrConf;
import cn.demo.um.service.IUmAttrConfService;
import cn.demo.um.support.Constant;
import cn.demo.um.support.handler.MatcherHandlerWrapper;
import cn.demo.um.support.handler.base.IBaseMatcherHandler;
import cn.demo.um.support.handler.base.PluralBaseMatcherHandler;
import cn.demo.um.support.handler.base.RangeBaseMatcherHandler;
import cn.demo.um.support.handler.base.SingleBaseMatcherHandler;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class MatcherHandlerFactory {
    private static final Map<String, IBaseMatcherHandler> BASE_MATCHER_MAP = new HashMap<>();

    @Autowired
    private PluralBaseMatcherHandler pluralMatcherHandler;
    @Autowired
    private RangeBaseMatcherHandler rangeMatcherHandler;
    @Autowired
    private SingleBaseMatcherHandler singleMatcherHandler;

    @Autowired
    private IUmAttrConfService umAttrConfService;

    /*小东西，访问次数多，存本地*/
    private Map<String, MatcherHandlerWrapper> handlerWrapperMap=null;

    @PostConstruct
    public void init() {
        /*为每个可选项类型注册对应的处理器*/
        BASE_MATCHER_MAP.put("inputNumber", rangeMatcherHandler);
        BASE_MATCHER_MAP.put("select", pluralMatcherHandler);
        BASE_MATCHER_MAP.put("checkbox", pluralMatcherHandler);
        BASE_MATCHER_MAP.put("radio", pluralMatcherHandler);
    }


    /**
     * 构建出所有的择偶标准对应的处理器，并额外包装一层
     * @return
     */
    public synchronized void resetHandlerMap() {
        List<UmAttrConf> list = umAttrConfService.queryChain()
                .eq(UmAttrConf::getIsStandard, Constant.SEARCH_STANDARD_TAG)
                .list();
        Map<String, MatcherHandlerWrapper> map = new HashMap<>();
        for (UmAttrConf umAttrConf : list) {
            IBaseMatcherHandler matcher = BASE_MATCHER_MAP.get(umAttrConf.getViewType());
            /*包装执行器和其属性*/
            MatcherHandlerWrapper matcherHandlerWrapper = new MatcherHandlerWrapper(umAttrConf.getAttrCode(), matcher, umAttrConf.getSort());
            map.put(umAttrConf.getAttrCode(), matcherHandlerWrapper);
        }
        handlerWrapperMap = map;
    }

    public Map<String, MatcherHandlerWrapper> getHandlerMap() {
        if (handlerWrapperMap == null) {
            synchronized (this){
                if (handlerWrapperMap == null) {
                    resetHandlerMap();
                }
            }
        }
        return handlerWrapperMap;
    }
}
